rails routes の結果を構造化データとして扱いたい
たとえば JSON として出力したかったら、こんなふうにすればいい。Rails.application.routes でほしいデータにアクセスできるってことがわかった。ちなみに Ruby on Rails v7.1.3.3 で作業した。 code:lib/tasks/routes_json.rake
namespace :routes do
desc "Output routes as JSON"
task as_json: :environment do
require "json"
routes = Rails.application.routes.routes
puts JSON.pretty_generate(
routes.map { |route|
path = route.path.spec.to_s
verb = route.verb.to_s
{ path:, verb:, controller:, action: }
}
)
end
end
code:sh
$ rails routes:as_json
[
{
"path": "/rails/mailers(.:format)",
"verb": "GET",
"controller": "rails/mailers",
"action": "index"
},
{
"path": "/rails/mailers/download/*path(.:format)",
"verb": "GET",
"controller": "rails/mailers",
"action": "download"
},
{
"path": "/rails/mailers/*path(.:format)",
"verb": "GET",
"controller": "rails/mailers",
"action": "preview"
},
...(中略)...
]
https://scrapbox.io/files/66508acf1848a9001ded9c23.webp